import { toAntcipatedFreight } from 'api/user.js'
import {  AntcipatedFreight,validata } from '@/model/antcipatedFreight.js'
import { Toast } from 'vant'
const state = {
  indexConfig:true, //初始化 首页 使用vuex 管理 不允许在页面中 单独处理 此状态
  userName: '',
  token: '',
  userInfo:'{}',
  consignorInfo:"{}",
  receiverInfo:"{}",
  weight:"",
  price:'0'

}
const mutations = {
  CLOSEINDEX(state){
    state.indexConfig=false
  },
  OPENINDEX(state){
    state.indexConfig=true
  },
  SET_USER_NAME(state, name) {
    state.userName = name
  },
  SET_TOKEN(state, token) {
    state.token = token
  },
  SET_USERINFO(state,userInfo){
    state.userInfo=userInfo
  },
  SET_ConsignorInfo(state,consignorInfo){
    state.consignorInfo=consignorInfo
    antcipatedFreight(state.consignorInfo,state.receiverInfo,state.weight)
  },
  SET_ReceiverInfo(state,receiverInfo){
    state.receiverInfo=receiverInfo
    antcipatedFreight(state.consignorInfo,state.receiverInfo,state.weight)
  },
  SET_Weight(state,weight){
    state.weight=weight
    antcipatedFreight(state.consignorInfo,state.receiverInfo,state.weight)
  }
 
}
const actions = {
  openIndex({ commit }){
    commit('OPENINDEX')
  },
  closeIndex({commit}){
    commit('CLOSEINDEX')
  },


  // 设置name
  setUserName({ commit }, name) {
    commit('SET_USER_NAME', name)
  },
  //设置token
  setToken({ commit }, token) {
    commit('SET_TOKEN', token)
  },
  //用户信息
  setUserInfo({ commit }, userInfo) {
    commit('SET_USERINFO', userInfo)
  },
  //首页寄件信息
  setConsignorInfo({ commit }, consignorInfo) {
    commit('SET_ConsignorInfo', consignorInfo)
  },
  //首页收件信息
  setReceiverInfo({ commit }, receiverInfo) {
    commit('SET_ReceiverInfo', receiverInfo)
  },
  //物件 重量
  setWeight({ commit }, weight){
    commit('SET_Weight', weight)
  }
 
}
export function antcipatedFreight(consignorInfo,receiverInfo,weight){
  const shipCity  =JSON.parse(consignorInfo).cityId ||""
  const receiveCity  =JSON.parse(receiverInfo).cityId ||""
  // console.log(shipCity,receiveCity,weight)
  // toAntcipatedFreight(data)
  let phone=  JSON.parse(state.userInfo).phone||""

  let antcipatedFreight=new AntcipatedFreight(shipCity,receiveCity,weight,phone)
  console.log("antcipatedFreight",antcipatedFreight)
  if(validata(antcipatedFreight,AntcipatedFreight)){
    let data=antcipatedFreight._getData()
    toAntcipatedFreight(data).then(res=>{
      console.log(res.data.result)
      state.price=res.data.result
    }).catch(err=>{
        Toast.fail({
          message:err
        })
    })
  }else{
    state.price=0
  }
}



export default {
  state,
  mutations,
  actions
}
